/**
* @description: 物资到货/施工现场负责人/ 监理人员 施工单位负责人 省信通管控人员只查看 省信通管控人员有代办
* @author: JiWei
* @remark: 通过store存储的权限判断页面显示部分
**/
<template>
  <view class="arrive-container">
    <nav-bar class="header" :background="backgroundColor" back title="物资到货" @goBack="goBack" />
    <view class="arrive-content">
      <plateTitle title="基本信息" :isRequired="false" class="plate-title" />
      <view class="basic-info">
        <van-form ref="ruleForm">
          <van-field v-model="arriveForm.projectName" label="工程名称" placeholder="请选择工程名称" type="textarea" autosize rows="1" disabled :rules="[{ required: true, trigger:'onSubmit'}]" input-align="right"
            required right-icon="arrow" error-message-align="right" @click="onOpenPicker('projectName')" />
          <van-field v-model="arriveForm.siteName" label="站点名称" placeholder="请选择站点名称" :rules="[{ required: true, trigger:'onSubmit'}]" disabled input-align="right" required right-icon="arrow"
            error-message-align="right" @click="onOpenPicker('siteName')" />
          <van-field v-model="arriveForm.arriveLocations" label="到货地点" placeholder="请输入到货地点" required input-align="right" error-message-align="right"
            :rules="[{ required: true,trigger:'onChange', message: '' }]" />
          <van-field required disabled :rules="[{ required: true, trigger:'onSubmit'}]" input-align="right" v-model="arriveForm.arriveTime" clearable label="到货时间" placeholder="请选择" right-icon="arrow"
            @click-right-icon="openPicker('arriveTime')" />
          <van-field v-model="arriveForm.personName" label="签收人" placeholder="请输入签收人" required input-align="right" error-message-align="right"
            :rules="[{ required: true,trigger:'onChange', message: '' }]" />
          <van-field required disabled :rules="[{ required: true, trigger:'onSubmit'}]" input-align="right" v-model="arriveForm.signforTime" clearable label="签收时间" placeholder="请选择" right-icon="arrow"
            @click-right-icon="openPicker('signforTime')" />
        </van-form>
      </view>
      <!-- 物资全貌  -->
      <view>
        <plateTitle title="物资全貌" :isRequired="false" class="plate-title" />
        <view class="overall-materials">
          <view class="image-list">
            <view class="upload-button" v-for="(imgItem, imgIndex) in fileList" :key="imgIndex" @click.stop="imageHandle(imgIndex,imgItem,'CHOOSE','materials')">
              <view v-if="imgItem.img" class="delete-icon" @click.stop="imageHandle(imgIndex,imgItem, 'DELETE','materials')">
                ×</view>
              <img v-if="imgItem.img" :src="imgItem.img" alt="" @click.stop="imageHandle(imgIndex,imgItem, 'PREVIEW','materials')">
            </view>
          </view>
        </view>
      </view>
      <!-- 到货清单    -->
      <view>
        <plateTitle title="到货清单" smallTitle="签收人及监理签字,并上传照片" :isRequired="false" :isShow="showToast" class="plate-title">
          <slot>
            <img src="../../../../static/controlImg/wzdh.png" alt="" @click="showTooltip" class="iconToast">
          </slot>
        </plateTitle>
        <view class="overall-materials">
          <view class="image-list">
            <view class="upload-button" v-for="(imgItem, imgIndex) in fileArrivalList" :key="imgIndex" @click.stop="imageHandle(imgIndex,imgItem,'CHOOSE','arrival')">
              <view v-if="imgItem.img" class="delete-icon" @click.stop="imageHandle(imgIndex,imgItem, 'DELETE','arrival')">
                ×</view>
              <img v-if="imgItem.img" :src="imgItem.img" alt="" @click.stop="imageHandle(imgIndex,imgItem, 'PREVIEW','arrival')">
            </view>
          </view>
        </view>
      </view>
    </view>
    <footer>
      <van-button block native-type="submit" @click="goToJump">保存</van-button>
      <van-button block native-type="submit" @click="goToPreview" :disabled="isDisabled">预览</van-button>
    </footer>
    <!-- 选择工程名称 -->
    <van-popup v-model="showSelectProject" position="bottom">
      <van-picker :title="pickerName" ref="typePicker" show-toolbar :columns="projectNameColumns" @confirm="onConfirm" @cancel="showSelectProject = false" />
    </van-popup>
    <!--  选择站点名称  -->
    <van-popup v-model="showSelectSite" position="bottom">
      <van-picker :title="pickerName" ref="typePicker" show-toolbar :columns="siteNameColumns" @confirm="onConfirmSite" @cancel="showSelectSite = false" />
    </van-popup>
    <!--时间选择器-->
    <van-popup v-model="showDatetimePicker" position="bottom">
      <van-datetime-picker :formatter="pickerFormatter" cancel-button-text="清空" @confirm="onDatetimeConfirm" @cancel="onDatetimeEmpty" v-model="currentDate" :min-date="minDate" />
    </van-popup>
    <van-popup class="van-preview-wrap" v-model="showPreview" @click="showPreview = false">
      <van-swipe>
        <div v-for="(image, index) in files" :key="index">
          <van-swipe-item v-if="image.img" style="text-align: center;">
            <img :src="image.img" />
          </van-swipe-item>
        </div>
      </van-swipe>
    </van-popup>
  </view>
</template>
<script>
import navBar from '../../../../components/common/nav-bar.vue'
import plateTitle from '../../common/plateTitle.vue'
import { mapGetters, mapMutations } from 'vuex'
import moment from 'moment/moment'
import { Dialog, Toast } from 'vant'
import wx from '../../../../static/common_js/jweixin_1.0.0'
import axios from 'axios'
import config from '../../../../common/config'
export default {
  name: 'index',
  components: { navBar, plateTitle },
  props: {},
  data() {
    return {
      baseUrl: '',
      showPreview: false,
      files: [],
      showToast: false,
      backgroundColor: '#417ADC',
      arriveForm: {
        projectName: '',
        projectId: '',
        arriveLocations: '',
        arriveTime: '',
        signforTime: '',
        personName: ''
      },
      showSelectProject: false,
      showSelectSite: false,
      projectNameColumns: [],
      siteNameColumns: [],
      pickerName: '工程名称',
      pickerType: '',
      endTime: '',
      beginTime: '',
      currentDate: '',
      minDate: new Date(0),
      showDatetimePicker: false,
      fileList: [
        {
          img: '',
          raw: null,
          type: ''
        }
      ],
      fileArrivalList: [
        {
          img: '',
          raw: null,
          type: ''
        }
      ],
      engId: null,
      engName: '',
      fileId: null,
      isDisabled: true,
      imgBase64: ''
    }
  },
  computed: {
    ...mapGetters(['userData', 'txgkAuth'])
  },
  watch: {},
  onLoad() {
    config.getOptions.then(res => {
      this.baseUrl = res.firstUrl;
      // this.baseUrl = 'http://192.168.0.127:18001';
    })
    this.userDataSet(this.userData)
    console.log(this.userData)
    this.getProjectName()
    // this.getSiteName();
  },
  methods: {
    ...mapMutations(['userDataSet']),
    showTooltip() {
      this.showToast = !this.showToast
    },
    // 获取工程名称
    getProjectName() {
      let params = {
        userId: this.userData.USERID
      }
      this.$apiRequest.gcgkApi.getEngListByUserId(params).then(res => {
        this.projectNameColumns = res.data.map(item => {
          if (item.SELECTDEFAULT === '1') {
            this.arriveForm.projectName = item.ENG_NAME
            this.engId = item.OBJ_ID
            if (this.engId !== null) {
              this.getSiteName()
            }
          }
          return {
            text: item.ENG_NAME,
            value: item.OBJ_ID
          }
        })
      })
      this.arriveForm.siteName = ''
      this.showSelectProject = false
    },
    onConfirmSite(value) {
      this.arriveForm.siteName = value.text
      this.arriveForm.siteId = value.value
      this.showSelectSite = false
    },
    // 获取站点名称
    getSiteName() {
      let params = {
        engId: this.engId,
        userId: this.userData.USERID
      }
      this.$apiRequest.gcgkApi.getEngSiteList(params).then(res => {
        this.siteNameColumns =
          res.data &&
          res.data.map(item => {
            return {
              text: item.stationName,
              value: item.stationId
            }
          })
      })
    },
    goToJump() {
      this.$refs.ruleForm.validate().then(() => {
        let params = {
          engId: this.engId,
          engName: this.arriveForm.projectName,
          signForUsername: this.arriveForm.personName,
          sighForTime: this.arriveForm.signforTime,
          stationId: this.arriveForm.siteId,
          stationName: this.arriveForm.siteName,
          arrivalTime: this.arriveForm.arriveTime,
          arrivalAddress: this.arriveForm.arriveLocations
        }
        Dialog.confirm({
          message: '是否确认提交？'
        }).then(() => {
          this.$apiRequest.gcgkApi.insertMaterial(params).then(res => {
            if (res.code == 0) {
              this.fileId = res.data
              this.submit()
            } else {
              Toast(res.msg)
            }
          })
        })
      })
    },
    onConfirm(value) {
      this.arriveForm.projectName = value.text
      this.engId = value.value
      this.showSelectProject = false
      this.getSiteName()
    },
    submit() {
      let param = new FormData()
      console.log(this.fileList.length, '===')
      if (this.fileList.length === 1) {
        Toast('请上传物资全貌照片！')
        return
      }
      if (this.fileArrivalList.length === 1) {
        Toast('请上传到货清单照片！')
        return
      }
      // let newArr = this.fileList.slice(0,-1).concat(this.fileArrivalList.slice(0,-1))
      this.fileList.forEach((item, index, arr) => {
        if (item.img) {
          // 去除最后一个
          param.append(`requests[0].requests[${index}].file`, item.raw)
          param.append(`requests[0].requests[${index}].flag`, index + 1)
        }
      })
      param.append(`requests[0].jlid`, this.fileId)
      param.append(`requests[0].fl`, '6')
      this.fileArrivalList.forEach((item, index, arr) => {
        if (item.img) {
          // 去除最后一个
          param.append(`requests[1].requests[${index}].file`, item.raw)
          param.append(`requests[1].requests[${index}].flag`, index + 1)
        }
      })
      param.append(`requests[1].jlid`, this.fileId)
      param.append(`requests[1].fl`, '7')
      let config = {
        headers: {
          'Content-Type': 'multipart/form-data',
          Authorization: uni.getStorageSync('token') || ''
        }
      }
      let url = ''
      // #ifndef IGW
      url = '/ap/txgcgk/api/file/uploads'
      // #endif
      // #ifdef IGW
      url = `${this.baseUrl}/txgcgk/api/file/uploads`
      // url = `http://192.168.124.75:18001/txgcgk/api/file/uploads`
      // #endif
      axios.post(url, param, config).then(res => {
        Toast.clear()
        if (res.data.code == 0) {
          this.isDisabled = false
          // uni.navigateTo({
          //   url: '/pages/communicationControl/index/index'
          // })
          Toast('提交成功')
        } else {
          Toast.clear()
          Toast('提交失败')
        }
      })
    },
    goBack() {
      uni.navigateTo({
        url: '/pages/communicationControl/index/index'
      })
    },
    goToPreview() {
      uni.navigateTo({
        url: `/pages/communicationControl/workbench/arrivalofMaterials/materialPreview?engId=${this.engId}&stationId=${this.arriveForm.siteId}&siteName=${this.arriveForm.siteName}&engName=${this.arriveForm.projectName}`
      })
    },
    onOpenPicker(e) {
      console.log(e)
      if (e === 'projectName') {
        this.showSelectProject = true
      } else if (e === 'siteName') {
        if (this.arriveForm.projectName === '') {
          Dialog.alert({
            message: '请先选择工作名称',
            theme: 'round-button'
          })
        } else {
          this.pickerName = '站点名称'
          this.showSelectSite = true
        }
      }
    },
    openPicker(pickerType) {
      if (pickerType === 'arriveTime') {
        this.currentDate =
          this.arriveForm.arriveTime !== ''
            ? new Date(this.arriveForm.arriveTime)
            : new Date()
        console.log(this.currentDate, 23232)
      } else if (pickerType === 'signforTime') {
        this.currentDate =
          this.arriveForm.signforTime !== ''
            ? new Date(this.arriveForm.signforTime)
            : new Date()
      }
      this.pickerType = pickerType
      this.showDatetimePicker = true
    },
    pickerFormatter(type, val) {
      if (type === 'year') return val + '年'
      if (type === 'month') return val + '月'
      if (type === 'day') return val + '日'
      if (type === 'hour') return val + '时'
      if (type === 'minute') return val + '分'
    },
    onDatetimeConfirm(time) {
      let timeString = ''
      timeString = moment(time).format('YYYY-MM-DD HH:mm')
      if (this.pickerType === 'arriveTime') {
        this.arriveForm.arriveTime = timeString
        if (
          this.arriveForm.signforTime !== '' &&
          new Date(this.arriveForm.signforTime).getTime() <
            new Date(this.arriveForm.arriveTime).getTime()
        ) {
          Dialog.alert({
            message: '到货时间不可晚于签收时间',
            theme: 'round-button'
          })
          this.arriveForm.arriveTime = ''
        }
      } else if (this.pickerType === 'signforTime') {
        this.arriveForm.signforTime = timeString
        if (
          this.arriveForm.arriveTime !== '' &&
          new Date(this.arriveForm.signforTime).getTime() <
            new Date(this.arriveForm.arriveTime).getTime()
        ) {
          Dialog.alert({
            message: '签收时间不可早于到货时间',
            theme: 'round-button'
          })
          this.arriveForm.signforTime = ''
        }
      }
      this.showDatetimePicker = false
    },
    imageHandle(imgIndex, imgItem, handleType, type) {
      this.currentType = type
      if (handleType === 'CHOOSE') {
        this.choosePhoto(imgIndex, imgItem, type)
      } else if (handleType === 'PREVIEW') {
        if (this.currentType === 'materials') {
          this.files = [imgItem]
        } else {
          this.files = [imgItem]
        }
        this.showPreview = true
      } else if (handleType === 'DELETE') {
        Dialog.confirm({
          title: `是否确认删除`
        })
          .then(() => {
            if (this.currentType === 'materials') {
              this.fileList.splice(imgIndex, 1)
              if (this.fileList.length < 9 && this.fileList[this.fileList.length-1].img) { // 最多上传9张 不够添加空对象
                this.fileList.push({img: '', raw: null, type: '', fl: '6'})
              }
            } else {
              this.fileArrivalList.splice(imgIndex, 1)
              if (this.fileArrivalList.length < 9 && this.fileArrivalList[this.fileArrivalList.length-1].img) { // 最多上传9张 不够添加空对象
                this.fileArrivalList.push({img: '', raw: null, type: '', fl: '7'})
              }
            }

          })
          .catch(() => {})
      }
    },
    choosePhoto1(imgIndex, imgItem, type) {
      let _this = this

      const photoName = `${new Date().getTime()}`
      if (type === 'materials') {
        _this.$set(_this.fileList, imgIndex, {
          raw: _this.dataURLtoFile(this.imgBase64, `${photoName}.jpeg`),
          img: this.imgBase64,
          type: imgItem.type,
          fl: '6'
        })

        if (
          _this.fileList.length < 9 &&
          _this.fileList[_this.fileList.length - 1].img
        ) {
          // 最多上传9张 不够添加空对象
          _this.fileList.push({
            img: '',
            raw: null,
            type: '',
            fl: '6'
          })
        }
      } else {
        _this.$set(_this.fileArrivalList, imgIndex, {
          raw: _this.dataURLtoFile(this.imgBase64, `${photoName}.jpeg`),
          img: this.imgBase64,
          type: imgItem.type,
          fl: '7'
        })
        if (
          _this.fileArrivalList.length < 9 &&
          _this.fileArrivalList[_this.fileArrivalList.length - 1].img
        ) {
          // 最多上传9张 不够添加空对象
          _this.fileArrivalList.push({
            img: '',
            raw: null,
            type: '',
            fl: '7'
          })
        }
      }

      // if (_this.fillData[_this.curTypeIndex].fileList.length < 9) {
      //   // 最多上传9张 不够添加空对象
      //   if (_this.fillData[_this.curTypeIndex].fileList[_this.fillData[_this.curTypeIndex].fileList.length-1].img) {
      //     _this.fillData[_this.curTypeIndex].fileList.push({img: '', raw: null, type: '', bgImg: require("../../../../static/controlImg/bg_pz.png")})
      //   }
      // }
    },
    choosePhoto(imgIndex, imgItem, type) {
      console.log(this.currentType, 'currentType')
      let _this = this
      wx.chooseImage({
        count: 1,
        sourceType: ['album', 'camera'],
        success: chooseImageRes => {
          wx.getLocalImgData({
            localId: chooseImageRes.localIds[0].toString(),
            success: function (res) {
              const localData = res.localData
              let imageBase64 = ''
              if (localData.indexOf('data:image') == 0) {
                //苹果的直接赋值，默认生成'data:image/jpeg;base64,'的头部拼接
                imageBase64 = localData
              } else {
                //此处是安卓中的唯一得坑！在拼接前需要对localData进行换行符的全局替换
                //此时一个正常的base64图片路径就完美生成赋值到img的src中了
                imageBase64 =
                  'data:image/jpeg;base64,' + localData.replace(/\n/g, '')
              }
              const photoName = `${new Date().getTime()}`
              if (type === 'materials') {
                _this.$set(_this.fileList, imgIndex, {
                  raw: _this.dataURLtoFile(imageBase64, `${photoName}.jpeg`),
                  img: imageBase64,
                  type: imgItem.type,
                  fl: '6'
                })
                // console.log('cccc', _this.dataURLtoFile(imageBase64,`${photoName}.jpeg`))

                if (_this.fileList.length < 9 && _this.fileList[_this.fileList.length - 1].img) {
                  // 最多上传9张 不够添加空对象
                  _this.fileList.push({
                    img: '',
                    raw: null,
                    type: '',
                    fl: '6'
                  })
                }
              } else {
                _this.$set(_this.fileArrivalList, imgIndex, {
                  raw: _this.dataURLtoFile(imageBase64, `${photoName}.jpeg`),
                  img: imageBase64,
                  type: imgItem.type,
                  fl: '7'
                })
                // console.log('cccc', _this.dataURLtoFile(imageBase64,`${photoName}.jpeg`))
                if (_this.fileArrivalList.length < 9  && _this.fileArrivalList[_this.fileArrivalList.length - 1].img) {
                  // 最多上传9张 不够添加空对象
                  _this.fileArrivalList.push({
                    img: '',
                    raw: null,
                    type: '',
                    fl: '7'
                  })
                }
              }
            }
          })
        },
        fail: error => {}
      })
    },
    dataURLtoFile(dataurl, filename) {
      var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], filename, { type: mime })
    },
    onDatetimeEmpty() {
      this.showDatetimePicker = false
      if (this.pickerType === 'arriveTime') {
        this.arriveForm.arriveTime = ''
      } else if (this.pickerType === 'signforTime') {
        this.arriveForm.signforTime = ''
      }
    }
  }
}
</script>
<style scoped lang="scss">
.arrive-container {
  width: 100vw;
  height: 100vh;
  background: #f2f6fa;
  .arrive-content {
    width: calc(100vw - #{px2vw(60)});
    height: calc(100vh - #{px2vh(380)});
    margin: px2vh(30);
    background: #f2f6fa;
    overflow: auto;
    .plate-title {
      margin-bottom: px2vh(30);
      .iconToast {
        width: px2vw(50);
        vertical-align: middle;
      }
    }
    .basic-info {
      height: auto;
      margin-bottom: px2vh(50);
    }
    .overall-materials {
      width: 100%;
      display: flex;
      margin-bottom: px2vh(30);
      background: #fff;
      .image-list {
        width: 100%;
        display: flex;
        flex-wrap: wrap;
        padding-top: px2vh(49);
        box-sizing: border-box;
        img {
          width: px2vw(230);
          height: px2vw(230);
          border-radius: px2vw(6);
        }
        .upload-button {
          width: px2vw(230);
          height: px2vw(230);
          flex-shrink: 0;
          position: relative;
          background-image: url('../../../../static/controlImg/bg_pz.png');
          background-size: 100% px2vw(230);
          margin: 0 calc((100% - #{px2vw(690)}) / 6) px2vh(45)
            calc((100% - #{px2vw(690)}) / 6);
          .delete-icon {
            position: absolute;
            top: px2vw(-20);
            right: px2vw(-20);
            width: px2vw(40);
            height: px2vw(40);
            background-color: rgba(0, 0, 0, 0.7);
            border-radius: 50%;
            color: #fff;
            display: flex;
            justify-content: center;
            align-items: center;
          }
        }
      }
    }
  }
  .footer {
    width: calc(100% - #{px2vw(60)});
    margin-left: px2vw(30);
    height: px2vh(180);
    background: #ffffff;
    border-top: px2vh(1) solid #e5e5e5;
    box-sizing: border-box;
    padding-top: px2vh(28);
  }
  .van-preview-wrap {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;

    .van-swipe {
      width: 100%;
      height: 60%;

      .van-swipe-item {
        display: flex;
        align-items: center;

        img {
          width: 100%;
        }
      }
    }
  }
  /deep/.van-button {
    width: px2vw(460);
    height: px2vh(120);
    color: #fff;
    margin-left: px2vw(52);
    float: left;
    background-color: #417adc;
    border: 1px solid #417adc;
    border-radius: px2vh(60);
  }
}
</style>
